from django.shortcuts import render, redirect
from app01 import models
from app01.utils.form import UserModelForm
from app01.utils.pagination import Pagination


def user_list(request):
    if request.method == "GET":
        queryset = models.UserInfo.objects.all()
        # python 中处理
        #     obj.name
        #     obj.age
        #     obj.password
        #     obj.account
        #     obj.create_time.strftime("%Y-%m-%d")  # html中  obj.create_time|date:"Y-m-d H:i:s"
        #     obj.depart.title                      # html中  同
        #     obj.get_gender_display()              # html中  不用加()，需要的时候会自动加（）
        page_object = Pagination(request, queryset, page_size=3)
        context = {
            "queryset": page_object.page_queryset,  # 分完页数据
            "page_string": page_object.html(),  # 页码
        }
        return render(request, 'user_list.html', context)

    # models.UserInfo.objects.create(name="京东",
    #                                age=23,
    #                                password="zxcvbn",
    #                                account=12000,
    #                                create_time="2033-11-11",
    #                                depart_id=2,
    #                                gender=1, )


def user_add(request):
    """添加用户 基于ModelForm"""
    # if request.method == "GET":
    #     content={
    #         'gender_choice':models.UserInfo.gender_choices,
    #         'depart_chioce':models.Department.objects.all()
    #     }
    #     return render(request,"user_add.html")
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_add.html', {"form": form})

    # 用户POST提交数据，需要数据校验，数据不允许为空
    if request.method == "POST":
        form = UserModelForm(data=request.POST)
        if form.is_valid():
            # print(form.cleaned_data)
            # {'name': '你好你', 'password': '121121', 'age': 32, 'account': Decimal('121221'), 'create_time': datetime.datetime(2011, 3, 21, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'depart': <Department: 信息运维部>, 'gender': 1}
            form.save()
            return redirect("/user/list")
        # 校验失败
        return render(request, 'user_add.html', {"form": form})


def user_edit(request, nid):
    """ 编辑用户 """
    # 根据id获取要编辑行原始数据
    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == "GET":
        # instance=row_object,默认显示初始值
        form = UserModelForm(instance=row_object)
        return render(request, "user_edit.html", {"form": form})

    if request.method == "POST":
        form = UserModelForm(data=request.POST, instance=row_object)
        if form.is_valid():
            # 默认保持用户输入的所有数据，若想在此基础上再添加字段可以
            # 自定义一个数据，form.instance.字段名 =值
            form.save()
            return redirect("/user/list/")
        # 校验失败<span style="color: red;">{{field.errors.0}}</span>
        return render(request, 'user_add.html', {"form": form})


def user_delete(request, nid):
    """ 删除用户 """
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")

